/*
 * ChainCommandLineParser.java
 *
 *  Copyright (C) 2010 Tal Eisenberg
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package drivechain;

import com.townleyenterprises.command.CommandListener;
import com.townleyenterprises.command.CommandOption;
import com.townleyenterprises.command.RepeatableCommandOption;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import tal.drivechain.chain.AbortChainException;
import tal.drivechain.chain.Chain;
import tal.drivechain.system.Globals;
import tal.drivechain.chain.ParallelPatcher;
import tal.drivechain.chain.Patcher;
import tal.drivechain.chain.SerialPatcher;
import tal.drivechain.chain.script.ScriptCommand;
import tal.drivechain.chain.script.ScriptCompiler;
import tal.drivechain.plugin.Module;
import tal.drivechain.system.PluginLoader;
import tal.drivechain.variable.Variable;


/**
 *
 * @author Main
 */
public class ChainCommandLineParser implements CommandListener {
    public RepeatableCommandOption define = new RepeatableCommandOption("define", 'd', "<var name>:<var value>", "Stores a Global variable before building the chain. The order of the define commands is the order of the actual global var creation.");
    public PluginOption input = new PluginOption("input", 'i', "<input class>:properties", "specify an input class to use");
    public PluginOption output = new PluginOption("output",'o', "<output class>:properties", "specify an output class to use");
    public PluginOption parser = new PluginOption("parser", 'p', "<parser class>:properties", "add a parser to the signal line");
    public CommandOption chainCommand = new PluginOption("patcher", 'c', "[serial/parallel]", "specify the chain patcher type");
    public RepeatableCommandOption runscript = new PluginOption("runscript", 'r', "script filename", "specify a script file to load. ignores any other options.");
    private CommandOption[] opts = new CommandOption[] { define, input, output, parser, chainCommand, runscript };

    public String getDescription() {
        return "Create chain options";
    }

    public CommandOption[] getOptions() {
        return opts;
    }

    public void optionMatched(CommandOption commandOption, String string) throws IllegalArgumentException {
    }
    
    public void createChain() throws AbortChainException {

        if (runscript.getMatched()) {
            if (define.getMatched() || chainCommand.getMatched() || input.getMatched() || output.getMatched() || parser.getMatched())
                throw new AbortChainException("--runscript can't be used with any other chain option (--define, --input, --patcher --output or --parser)");
            for (Object arg : runscript.getArgs()) {
                ScriptCompiler compiler = new ScriptCompiler();
                File scriptPath = ScriptCompiler.getScriptFile((String)arg, new File(System.getProperty("user.dir")), false);
                compiler.loadFromFile(scriptPath);
                compiler.parseScript();

                compiler.compileScript(Globals.getRootChain());                
            }
        } else {
            if (!define.getMatched() && !chainCommand.getMatched() && !parser.getMatched() && !output.getMatched() && !input.getMatched())
                return;
            
            Chain chain = new Chain("main");
            Globals.getRootChain().addChild(chain);
            if (define.getMatched()) {
                for (int i=0; i<define.getArgs().size(); i++) {
                    String args = (String)define.getArgs().get(i);

                    Variable def = Variable.parseVariable(null, null, args, false);
                    chain.storeChainVar(def.getName(), def);
                }
            }
            boolean isParallel;
            if (chainCommand.getMatched()) {
                if (chainCommand.getArgValue().equals("parallel"))
                    isParallel = true;
                else if (chainCommand.getArgValue().equals("serial"))
                    isParallel = false;
                else throw new IllegalArgumentException("Invalid chain command option value: " + chainCommand.getArgValue() + " should be 'serial' or 'parallel'.");
            } else isParallel = true;

            List<ScriptCommand> patches = new ArrayList<ScriptCommand>();
            Patcher patcher;
            if (isParallel)
                patcher = new ParallelPatcher();
            else patcher = new SerialPatcher();

            if (parser.getMatched()) {
                for (int i=0; i<parser.getArgs().size(); i++) {
                    Module parserModule = PluginLoader.getModule(parser.getName(i));
                    parserModule.parseProperties(parser.getProperties(i));
                    chain.addChild(parserModule);
                    patches.add(new ScriptCommand("parser", parserModule.getName(), ""));
                }
            }
            if (output.getMatched()) {
                for (int i=0; i<output.getArgs().size(); i++) {
                    Module outputModule = PluginLoader.getModule(output.getName(i));
                    outputModule.parseProperties(output.getProperties(i));
                    chain.addChild(outputModule);
                    patches.add(new ScriptCommand("output", outputModule.getName(), ""));
                }
            }
            if (input.getMatched()) {
                for (int i=0; i<input.getArgs().size(); i++) {
                    Module inputModule = PluginLoader.getModule(input.getName(i));
                    inputModule.parseProperties(input.getProperties(i));
                    chain.addChild(inputModule);
                    patches.add(new ScriptCommand("input", inputModule.getName(), ""));
                }
            }

            patcher.configure(patches);
            chain.patchNodes(patcher);
            chain.setupProperties();
        }
        

    }

}
